package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IApCollectionService;
import com.heima.article.task.ArticleTask;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-14
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {


    @Autowired
    private IApArticleContentService contentService;

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        // 需求分析
        // 判断是否包含文章id,有id的话需要更新文章
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        if (dto.getId() == null) {
            // 保存文章
            this.save(article);
            // 保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            // 自动生成静态页  通过异步的方式来操作
            System.out.println(Thread.currentThread().getName() + "开始调用异步文章静态页生成...");
            articleTask.createHtml(article, dto.getContent());

            return ResponseResult.okResult(article.getId());
        } else {
            // 更新文章
            this.updateById(article);
            // 更新文章内容
            LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
            update.eq(ApArticleContent::getArticleId, dto.getId());
            update.set(ApArticleContent::getContent, dto.getContent());
            contentService.update(update);
            return ResponseResult.okResult(dto.getId());
        }
    }

    @Autowired
    @Lazy
    private ArticleTask articleTask;

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type 0:最新文章  1:更多文章
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        // 构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        // 如果频道id不为空且不为0,添加频道条件
        if (dto.getChannelId() != null && dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        if (type == 0) {
            // 加载最新,查询比页面传递的最大时间更新的数据
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        } else {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        // 过滤已下架\已删除的文章
        query.eq(ApArticle::getIsDown, false);
        query.eq(ApArticle::getIsDelete, false);
        // 排序,按照发布时间倒序
        query.orderByDesc(ApArticle::getPublishTime);
        // 构建分页条件
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        // 执行分页查询
        IPage<ApArticle> iPage = this.page(page, query);
        // 返回通用响应
        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 根据id查询文章
        ApArticle article = this.getById(dto.getArticleId());
        // 根据文章id查询文章内容
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = contentService.getOne(query);
        // 构建响应
        Map<String, Object> map = new HashMap<>();
        map.put("config", article);
        map.put("content", content);
        return ResponseResult.okResult(map);
    }

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    IApCollectionService collectionService;


    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(user.getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());

        ApBehaviorEntry behavior = behaviorFeign.getBehavior(entryDto);
        Map<String,Boolean> map = new HashMap<>();
        map.put("isfollow",false);
        map.put("islike",false);
        map.put("isunlike",true);
        map.put("iscollection",false);

        FollowDto followDto = new FollowDto();
        followDto.setFollowId(dto.getAuthorId());

        LikeDto likeDto = new LikeDto();
        likeDto.setArticleId(dto.getArticleId());


        ApFollowBehavior follow = behaviorFeign.getFollow(followDto);

        if (follow!=null) {
            if (follow.getOperation()==0) {
                map.put("isfollow",true);
            }
        }


        ApLikesBehavior like = behaviorFeign.getLike(likeDto);
        if (like!=null) {
            if (like.getOperation()==0) {
                map.put("islike",true);
            }
        }

        ApUnlikesBehavior unLike = behaviorFeign.getUnLike(likeDto);
        if (unLike!=null) {
            if (unLike.getType()==1) {
                map.put("isunlike",false);
            }

        }

        ApCollection apCollection = collectionService.getApCollection(dto.getArticleId());

        if (apCollection!=null) {
            map.put("iscollection",true);
        }


        return ResponseResult.okResult(map);
    }
}
